using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using UwinEducation.Application.Common.Interfaces;
using UwinEducation.Application.Common.Interfaces.Orders;
using UwinEducation.Application.Dtos.Orders;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Shared.Enums;
using UwinEducation.Shared.Exceptions;
using UwinEducation.Shared.Models;

namespace UwinEducation.Application.Services.Orders
{
    /// <summary>
    /// 订单支付服务实现
    /// </summary>
    public class OrderPaymentService : IOrderPaymentService
    {
        private readonly IOrderPaymentRepository _orderPaymentRepository;
        private readonly IOrderRepository _orderRepository;

        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="orderPaymentRepository">订单支付仓储</param>
        /// <param name="orderRepository">订单仓储</param>
        /// <param name="unitOfWork">工作单元</param>
        /// <param name="mapper">映射器</param>
        public OrderPaymentService(
            IOrderPaymentRepository orderPaymentRepository,
            IOrderRepository orderRepository,
            IMapper mapper)
        {
            _orderPaymentRepository = orderPaymentRepository;
            _orderRepository = orderRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 根据ID获取订单支付详情
        /// </summary>
        /// <param name="id">支付ID</param>
        /// <returns>订单支付DTO</returns>
        public async Task<OrderPaymentDto> GetByIdAsync(Guid id)
        {
            var payment = await _orderPaymentRepository.GetByIdAsync(id);
            if (payment == null)
            {
                throw new ArgumentException($"未找到ID为 {id} 的支付记录");
            }
            return _mapper.Map<OrderPaymentDto>(payment);
        }

        /// <summary>
        /// 根据订单ID获取支付记录列表
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>订单支付DTO列表</returns>
        public async Task<List<OrderPaymentDto>> GetByOrderIdAsync(Guid orderId)
        {
            var payments = await _orderPaymentRepository.GetByOrderIdAsync(orderId);
            return _mapper.Map<List<OrderPaymentDto>>(payments);
        }

        /// <summary>
        /// 获取订单支付分页列表
        /// </summary>
        /// <param name="requestDto">分页请求DTO</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResult<OrderPaymentDto>> GetPagedListAsync(OrderPaymentPageRequestDto requestDto)
        {
            var request = _mapper.Map<OrderPaymentPageRequest>(requestDto);
            var result = await _orderPaymentRepository.GetPagedAsync(request);
            var dtoItems = _mapper.Map<List<OrderPaymentDto>>(result.Items);
            return new PagedResult<OrderPaymentDto>
            {
                Items = dtoItems,
                Total = result.Total
            };
        }

        /// <summary>
        /// 创建订单支付记录
        /// </summary>
        /// <param name="createDto">创建订单支付DTO</param>
        /// <returns>创建后的订单支付DTO</returns>
        public async Task<OrderPaymentDto> CreateAsync(CreateOrderPaymentDto createDto)
        {
            // 验证订单是否存在
            var order = await _orderRepository.GetByIdAsync(createDto.OrderId);
            if (order == null)
            {
                throw new ArgumentException($"未找到ID为 {createDto.OrderId} 的订单");
            }

            var payment= OrderPayment.Create(
                createDto.OrderId,
                createDto.StudentId,
                createDto.Amount,
                createDto.PaymentMethod,
                createDto.TransactionId,
                createDto.PaymentDate,
                createDto.CreatorId,
                createDto.Remarks??string.Empty
            );

            await _orderPaymentRepository.AddAsync(payment);

            //// 更新订单支付状态和金额
            //await UpdateOrderPaymentInfo(order.Id);

            // 重新获取以包含订单信息
            var createdPayment = await _orderPaymentRepository.GetByIdAsync(payment.Id);
            return _mapper.Map<OrderPaymentDto>(createdPayment);
        }

        /// <summary>
        /// 更新订单支付记录
        /// </summary>
        /// <param name="updateDto">更新订单支付DTO</param>
        /// <returns>更新后的订单支付DTO</returns>
        public async Task<OrderPaymentDto> UpdateAsync(UpdateOrderPaymentDto updateDto)
        {
            var payment = await _orderPaymentRepository.GetByIdAsync(updateDto.Id);
            if (payment == null)
            {
                throw new ArgumentException($"未找到ID为 {updateDto.Id} 的支付记录");
            }

            //// 验证订单是否改变，如果改变，不允许
            //if (payment.OrderId != updateDto.OrderId)
            //{
            //     throw new ArgumentException("不允许修改支付记录关联的订单ID");
            //}

            //var originalOrderId = payment.OrderId;
            //var originalStatus = payment.Status;

            payment.AuditStatus = updateDto.AuditStatus;
            payment.AuditorId = updateDto.AuditorId;
            payment.Remarks = updateDto.Remarks?? payment.Remarks;

            await _orderPaymentRepository.UpdateAsync(payment);

            //// 如果支付状态或金额改变，需要更新订单信息
            //if (originalStatus != payment.Status || payment.Amount != updateDto.Amount)
            //{
            //    await UpdateOrderPaymentInfo(originalOrderId);
            //}

            // 重新获取以包含更新后的关联信息
            var updatedPayment = await _orderPaymentRepository.GetByIdAsync(payment.Id);
            return _mapper.Map<OrderPaymentDto>(updatedPayment);
        }

        /// <summary>
        /// 删除订单支付记录
        /// </summary>
        /// <param name="id">支付ID</param>
        public async Task DeleteAsync(Guid id)
        {
            var payment = await _orderPaymentRepository.GetByIdAsync(id);
            if (payment == null)
            {
                throw new ArgumentException($"未找到ID为 {id} 的支付记录");
            }

            var orderId = payment.OrderId;

            await _orderPaymentRepository.DeleteAsync(id);

            //// 更新订单支付状态和金额
            //await UpdateOrderPaymentInfo(orderId);

            //await _unitOfWork.SaveChangesAsync();
        }

        /// <summary>
        /// 计算订单的总支付金额
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>总支付金额</returns>
        public async Task<decimal> GetTotalPaidAmountAsync(Guid orderId)
        {
            return await _orderPaymentRepository.GetTotalPaidAmountAsync(orderId);
        }

        /// <summary>
        /// 更新订单的支付状态和金额信息
        /// </summary>
        /// <param name="orderId">订单ID</param>
        //private async Task UpdateOrderPaymentInfo(Guid orderId)
        //{
        //    var order = await _orderRepository.GetByIdAsync(orderId);
        //    if (order == null)
        //    {
        //        // 订单不存在，记录日志或抛出异常，根据业务决定
        //        // 此处选择忽略，因为可能是并发删除导致
        //        return;
        //    }

        //    var totalPaid = await _orderPaymentRepository.GetTotalPaidAmountAsync(orderId);
        //    order.PaidAmount = totalPaid;

        //    // 更新订单支付状态
        //    if (totalPaid <= 0)
        //    {
        //        order.PaymentStatus = PaymentStatus.Unpaid;
        //    }
        //    else if (totalPaid >= order.TotalAmount - order.DiscountedAmount) // 考虑折扣
        //    {
        //        order.PaymentStatus = PaymentStatus.Paid;
        //    }
        //    else
        //    {
        //        order.PaymentStatus = PaymentStatus.PartialPaid;
        //    }

        //    await _orderRepository.UpdateAsync(order);
        //    // SaveChangesAsync 将由调用方（如CreateAsync, UpdateAsync等）的 UnitOfWork 处理
        //}
    }
} 